<?php

namespace App\Common\Http\Controller;

use App\ApiBaseController;
use App\Common\Services\SmsService;
use Illuminate\Support\Facades\Validator;

class SmsController extends ApiBaseController
{
    /**
     * 表单验证
     * @param $data
     * @param $type
     * @return bool
     * @throws GoodsException
     */
    protected function validate($data, $ruleArr, $source = '')
    {
        $rule = [
            'phone' => ['required', 'regex:/^((\(\d{2,3}\))|(\d{3}\-))?1(3|5|8|9)\d{9}$/'],
            'code' => 'required|integer',
            'type' => 'required|string'
        ];

        $message = [
            'phone.required' => '请输入登录手机号',
            'phone.regex' => '登录手机号格式异常',
            'code.required' => '请输入验证码',
            'code.integer' => '验证码必须为整数',
            'code.between' => '验证码长度应在4-6位',
            'type.required' => '请输入短信类型',
            'type.string' => '短息类型必须为字符串'
        ];

        // 根据配置选择规则组成
        $rule = array_intersect_key($rule, array_flip($ruleArr));

        $validate = Validator::make($data, $rule, $message);
        if($validate->fails()){
            throw new \Exception($validate->errors()->first());
        }
        return true;
    }

    /**
     * User: zhangchaoqun
     * DateTime: 2021/6/10 7:24 下午
     * Describe: 验证短信
     * Version: V1.0
     */
    public function verifyCode()
    {
        // 接受参数
        $params = request()->input();
        // 参数字段
        $fields = ['phone', 'code', 'type'];

        try {
            // 校验参数
            $this->validate($params, $fields);

            $smsService = new SmsService();
            $smsService->verifyCode($params['phone'], $params['code'], $params['type']);

            return $this->success('验证成功');
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * User: zhangchaoqun
     * DateTime: 2021/6/10 7:23 下午
     * Describe: 发送短信
     * Version: V1.0
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendCode()
    {
        // 接受参数
        $params = request()->input();
        // 参数字段
        $fields = ['phone', 'type'];

        try {
            // 校验参数
            $this->validate($params, $fields);

            $smsService = new SmsService();
            $smsService->sendCode($params['phone'],  $params['type']);

            return $this->success('发送成功');
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}
